package com.gitee.simons.oauth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gitee.simons.oauth.entity.po.OauthClientDetails;
import com.gitee.simons.oauth.mapper.OauthClientDetailsMapper;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * @author simon jiang
 * @time 2020/7/8 16:04
 */
@Service
public class MyClientDetailServiceImpl implements ClientDetailsService {

    @Autowired
    private OauthClientDetailsMapper oauthClientDetailsMapper;


    @Autowired
    private MapperFacade mapperFacade;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        OauthClientDetails oauthClientDetail = oauthClientDetailsMapper.selectOne(
                new QueryWrapper<OauthClientDetails>().lambda().eq(OauthClientDetails::getClientId, clientId));
        if (oauthClientDetail == null) {
            throw new SecurityException("没有对应的客户端信息");
        }
        BaseClientDetails baseClientDetails = new BaseClientDetails();
        baseClientDetails.setScope(Collections.emptyList());
        baseClientDetails.setResourceIds(Collections.EMPTY_LIST);
        baseClientDetails.setRegisteredRedirectUri(Collections.EMPTY_SET);
        baseClientDetails.setClientSecret(oauthClientDetail.getClientSecret());
        baseClientDetails.setClientId(clientId);
        baseClientDetails.setRefreshTokenValiditySeconds(oauthClientDetail.getRefreshTokenValidity());
        baseClientDetails.setAccessTokenValiditySeconds(oauthClientDetail.getAccessTokenValidity());
        baseClientDetails.setAuthorizedGrantTypes(Collections.EMPTY_LIST);
        baseClientDetails.setAutoApproveScopes(Collections.EMPTY_LIST);
        baseClientDetails.setAdditionalInformation(Collections.EMPTY_MAP);
        baseClientDetails.setAuthorities(Collections.EMPTY_LIST);
        return baseClientDetails;
    }
}
